package com.cyl.h5.controller;

import java.math.BigDecimal;
import java.util.List;

import com.cyl.manager.act.domain.entity.FhRechargeData;
import com.cyl.manager.act.service.FhRechargeDataService;
import com.cyl.manager.act.domain.query.FhRechargeDataQuery;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.cyl.manager.vip.domain.entity.VipOrder;
import com.cyl.manager.vip.service.IVipOrderService;
import com.cyl.h5.domain.form.VipPayForm;
import com.cyl.h5.domain.vo.VipPayVO;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.config.LocalDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * VIP支付Controller
 *
 * @author system
 */
@Api(tags = "VIP管理")
@RestController
@RequestMapping("/app/vip/payment")
public class H5VipPaymentController extends BaseController {
    @Autowired
    private IVipOrderService vipOrderService;

    @Autowired
    private FhRechargeDataService fhRechargeDataService;

    /**
     * 查询VIP配置列表
     */
    @ApiOperation("查询VIP配置列表")
    @GetMapping("/config/list")
    public AjaxResult getVipConfigList() {
        try {
            List<FhRechargeData> configList = fhRechargeDataService.selectList(new FhRechargeDataQuery(), null);
            return AjaxResult.success(configList);
        } catch (Exception e) {
            return AjaxResult.error("获取VIP配置失败：" + e.getMessage());
        }
    }

    /**
     * 创建VIP订单
     */
    @ApiOperation("创建VIP订单")
    @PostMapping("/create")
    public R<VipOrder> createVipOrder(@RequestBody CreateVipOrderRequest request)
    {
        try {
            // 获取当前用户ID
            UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
            Long userId = member.getId();

            // 查询VIP配置信息
            FhRechargeData rechargeData = fhRechargeDataService.selectById(request.getRechargeDataId());
            if (rechargeData == null) {
                return R.fail("VIP配置不存在");
            }

            // 计算订单金额
            BigDecimal amount = rechargeData.getPrice();
            BigDecimal payAmount = rechargeData.getDiscountPrice() != null ? rechargeData.getDiscountPrice() : amount;
            Integer vipDays = rechargeData.getDay();

            // 创建VIP订单
            VipOrder vipOrder = vipOrderService.createVipOrder(
                userId,
                request.getRechargeDataId(),
                vipDays,
                amount,
                payAmount,
                request.getPayType(),
                request.getIsAutoRenew()
            );

            return R.ok(vipOrder);
        } catch (Exception e) {
            return R.fail("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * VIP订单支付
     */
    @ApiOperation("VIP订单支付")
    @PostMapping("/pay")
    @Log(title = "VIP订单支付", businessType = BusinessType.INSERT)
    public AjaxResult vipOrderPay(@RequestBody VipPayForm vipPayForm) {
        try {

            UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
            Long userId = member.getId();
            vipPayForm.setUserId(userId);

            // 调用支付服务
            VipPayVO payResult = vipOrderService.vipOrderPay(vipPayForm);

            return AjaxResult.success("支付调用成功", payResult);
        } catch (Exception e) {
            return AjaxResult.error("支付调用失败：" + e.getMessage());
        }
    }

    /**
     * 查询VIP订单列表
     */
    @ApiOperation("查询VIP订单列表")
    @GetMapping("/order/list")
    public TableDataInfo list(VipOrder vipOrder) {
        startPage();
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long userId = member.getId();
        vipOrder.setUserId(userId);
        List<VipOrder> list = vipOrderService.selectVipOrderList(vipOrder);
        return getDataTable(list);
    }


    /**
     * 获取VIP订单详细信息
     */
    @ApiOperation("获取VIP订单详细信息")
    @GetMapping("/order/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(vipOrderService.selectVipOrderById(id));
    }

    /**
     * 根据订单号获取VIP订单详细信息
     */
    @ApiOperation("根据订单号获取VIP订单详细信息")
    @GetMapping("/order/sn/{orderSn}")
    public AjaxResult getInfoByOrderSn(@PathVariable("orderSn") String orderSn) {
        return AjaxResult.success(vipOrderService.selectVipOrderByOrderSn(orderSn));
    }

    /**
     * 根据用户ID获取VIP订单列表
     */
    @ApiOperation("根据用户ID获取VIP订单列表")
    @GetMapping("/order/user/{userId}")
    public AjaxResult getOrderListByUserId(@PathVariable("userId") Long userId) {
        List<VipOrder> list = vipOrderService.selectVipOrderListByUserId(userId);
        return AjaxResult.success(list);
    }

    /**
     * 修改VIP订单
     */
    @Log(title = "VIP订单", businessType = BusinessType.UPDATE)
    @PutMapping("/order")
    public AjaxResult edit(@RequestBody VipOrder vipOrder) {
        return toAjax(vipOrderService.updateVipOrder(vipOrder));
    }

    /**
     * 删除VIP订单
     */
    @Log(title = "VIP订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/order/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(vipOrderService.deleteVipOrderByIds(ids));
    }

    /**
     * 取消订单
     */
    @ApiOperation("删除VIP订单")
    @PostMapping("/order/cancel/{orderSn}")
    @Log(title = "取消VIP订单", businessType = BusinessType.UPDATE)
    public AjaxResult cancelOrder(@PathVariable("orderSn") String orderSn) {
        boolean result = vipOrderService.cancelOrder(orderSn);
        return result ? AjaxResult.success("订单取消成功") : AjaxResult.error("订单取消失败");
    }


    /**
     * 创建VIP订单请求对象
     */
    public static class CreateVipOrderRequest {
        private Long rechargeDataId;
        private Integer payType;
        private Boolean isAutoRenew; // 是否自动续费

        public Long getRechargeDataId() {
            return rechargeDataId;
        }

        public void setRechargeDataId(Long rechargeDataId) {
            this.rechargeDataId = rechargeDataId;
        }

        public Integer getPayType() {
            return payType;
        }

        public void setPayType(Integer payType) {
            this.payType = payType;
        }

        public Boolean getIsAutoRenew() {
            return isAutoRenew;
        }

        public void setIsAutoRenew(Boolean isAutoRenew) {
            this.isAutoRenew = isAutoRenew;
        }
    }

    /**
     * 支付回调请求对象
     */
    public static class PayCallbackRequest {
        private String orderSn;
        private String thirdPartyOrderSn;
        private Integer payType;

        public String getOrderSn() {
            return orderSn;
        }

        public void setOrderSn(String orderSn) {
            this.orderSn = orderSn;
        }

        public String getThirdPartyOrderSn() {
            return thirdPartyOrderSn;
        }

        public void setThirdPartyOrderSn(String thirdPartyOrderSn) {
            this.thirdPartyOrderSn = thirdPartyOrderSn;
        }

        public Integer getPayType() {
            return payType;
        }

        public void setPayType(Integer payType) {
            this.payType = payType;
        }
    }
}
